package com.lq.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lq.CodeEnnms.ApiResponseEnum;
import com.lq.pojo.ApiResponse;
import com.lq.util.ApiResponseUtil;
import com.lq.util.JwtUtil;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");
        //String token = response.getHeader("token");
        String token = request.getHeader("token");

        System.out.println("requestTokne:-->"+token);
        //System.out.println("Token："+access_token);
        System.out.println("之前的拦截器****************************************");
        //Token不存在
        if(token!=null){
            //验证token是否正确
            boolean result = JwtUtil.verify(token);
            System.out.println("验证token的结果:"+result);
            if(result){
                return true;
            }
        }
        //如果不存在 返回认证失败
        ApiResponse apiResponse= ApiResponseUtil.getApiResponse(ApiResponseEnum.AUTH_ERROR);
        responseMessage(response,response.getWriter(),apiResponse);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //之后
        System.out.println("退出拦截器");
    }

    /**
     * 返回消息给客户端
     * @param response
     * @param out
     * @param apiResponse
     */
    private void responseMessage(HttpServletResponse response, PrintWriter out, ApiResponse apiResponse){
        response.setContentType("application/json;charset=utf-8");
        out.print(JSONObject.toJSONString(apiResponse));
        out.flush();
        out.close();
    }

}
